package com.yuwubao.framework.log;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.ValueFilter;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * <Description> <br>
 *
 * @author wk <br>
 * @version 1.0<br>
 * @taskId <br>
 * @CreateDate 2017/7/4 <br>
 * @see com.yuwubao.framework.log <br>
 * @since V1.0<br>
 */
@Aspect
@Configuration
public class LogRecordAspect {

    private static final Logger logger = LogManager.getLogger(LogRecordAspect.class);

    /**
     * 定义切点Pointcut
     */
    @Pointcut("execution(* com.yuwubao..*Controller.*(..))")
    public void executeService() {
    }

    /**
     * @param pjp
     * @return
     * @throws Throwable
     */
    @Around("executeService()")
    public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
        RequestAttributes ra = RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes) ra).getRequest();

        String uri = request.getRequestURI();

        // 记录入口参数
        logger.debug("URI: [ {} ], Inlet-Parameters: {}", uri, JSON.toJSONString(request.getParameterMap(), new ValueFilter() {
            @Override
            public Object process(Object o, String s, Object o1) {
                if (o1 instanceof String[] && ((String[]) o1).length > 0) {
                    o1 = ((String[]) o1)[0];
                }
                return o1;
            }
        }));

        //执行controller业务
        Object result = pjp.proceed();

        // 记录出口参数
        //String outletParameters = JSON.toJSONString(result, SerializerFeature.PrettyFormat);
        logger.debug("URI: [ {} ], Outlet-Parameters: {}", uri, JSON.toJSONString(result));
        return result;
    }
}
